"""
管理员界面配置
"""
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask_login import current_user
from flask import redirect, url_for, request
from sqlalchemy.orm import scoped_session, sessionmaker

from modules.models.base import engine
from modules.models import (
    SecurityInfo, DailyQuote, TechnicalIndicator, CollectionTask,
    EconomicNews, StockNotice, MacroEconomicData, EconomicCalendar,
    FinancialStatement, ValuationIndicator, FinancialRatio
)


# 创建数据库会话
Session = scoped_session(sessionmaker(bind=engine))


class SecureModelView(ModelView):
    """安全的模型视图基类，需要登录且具有管理员权限"""
    
    def is_accessible(self):
        """检查当前用户是否可以访问"""
        return current_user.is_authenticated and current_user.is_admin
    
    def inaccessible_callback(self, name, **kwargs):
        """当用户无法访问时的回调函数"""
        return redirect(url_for('login', next=request.url))


class SecurityInfoView(SecureModelView):
    """证券信息管理视图"""
    column_list = ['code', 'name', 'type', 'exchange', 'industry', 'is_active']
    column_searchable_list = ['code', 'name', 'type', 'exchange', 'industry']
    column_filters = ['type', 'exchange', 'is_active']


class DailyQuoteView(SecureModelView):
    """每日行情管理视图"""
    column_list = ['security.code', 'security.name', 'trade_date', 'open', 'high', 'low', 'close', 'volume']
    column_searchable_list = ['security.code', 'security.name', 'trade_date']
    column_filters = ['security.type', 'trade_date']


class CollectionTaskView(SecureModelView):
    """采集任务管理视图"""
    column_list = ['task_type', 'security_code', 'start_date', 'end_date', 'status', 'result_count', 'create_time']
    column_searchable_list = ['task_type', 'security_code', 'status']
    column_filters = ['task_type', 'status', 'create_time']


class EconomicNewsView(SecureModelView):
    """经济新闻管理视图"""
    column_list = ['title', 'source', 'category', 'publish_time']
    column_searchable_list = ['title', 'source', 'category']
    column_filters = ['source', 'category', 'publish_time']


class MacroEconomicDataView(SecureModelView):
    """宏观经济数据管理视图"""
    column_list = ['indicator', 'region', 'period', 'time_point', 'value', 'unit']
    column_searchable_list = ['indicator', 'region']
    column_filters = ['indicator', 'region', 'time_point']


class FinancialStatementView(SecureModelView):
    """财务报表管理视图"""
    column_list = ['security.code', 'security.name', 'report_type', 'fiscal_period', 'report_date', 'item_name', 'item_value']
    column_searchable_list = ['security.code', 'report_type', 'item_name']
    column_filters = ['report_type', 'fiscal_period', 'report_date']


def setup_admin(app):
    """设置Admin管理界面"""
    admin = Admin(app, name='金融数据平台', template_mode='bootstrap4')
    
    # 创建数据库会话
    session = Session()
    
    # 添加模型视图
    admin.add_view(SecurityInfoView(SecurityInfo, session, name='证券信息', category='基础数据'))
    admin.add_view(DailyQuoteView(DailyQuote, session, name='每日行情', category='行情数据'))
    admin.add_view(CollectionTaskView(CollectionTask, session, name='采集任务', category='系统管理'))
    
    # 新闻和宏观经济数据管理
    admin.add_view(EconomicNewsView(EconomicNews, session, name='财经新闻', category='新闻资讯'))
    admin.add_view(SecureModelView(StockNotice, session, name='股票公告', category='新闻资讯'))
    admin.add_view(MacroEconomicDataView(MacroEconomicData, session, name='宏观经济数据', category='宏观数据'))
    admin.add_view(SecureModelView(EconomicCalendar, session, name='经济日历', category='宏观数据'))
    
    # 财务数据管理
    admin.add_view(FinancialStatementView(FinancialStatement, session, name='财务报表', category='财务数据'))
    admin.add_view(SecureModelView(ValuationIndicator, session, name='估值指标', category='财务数据'))
    admin.add_view(SecureModelView(FinancialRatio, session, name='财务比率', category='财务数据'))
    
    # 技术指标管理
    admin.add_view(SecureModelView(TechnicalIndicator, session, name='技术指标', category='技术分析'))
    
    return admin